Array Operations

In this lesson, we will learn about scalar and element-wise array operations.

As we have seen in previous lessons, Python vectors and matrices are not equivalent to mathematical matrices, but they are similar in some ways.

Keep in mind that certain Python vector and matrix operations differ from the mathematical vector and matrices.

Scalar operations#

We can use the usual arithmetic operators to multiply, add, subtract, and divide arrays with scalar numbers. These operations will be performed individually on each element.

Let’s see the implementation for vectors below:

The same rules apply for matrices as well. See the example below:

Element-wise operation#

When we add, subtract, divide or multiply arrays, values are operated element-wise. Each element is operated against its corresponding index.

Created with Fabric.js 1.6.0-rc.1 + 1 3 4 6 7 9 2 6 1 3 7 9

1 of 4

Created with Fabric.js 1.6.0-rc.1 + + + + + + 1 3 4 6 7 9 2 6 1 3 7 9

2 of 4

Created with Fabric.js 1.6.0-rc.1 1+2 3+6 4+1 6+3 7+7 9+9

3 of 4

Created with Fabric.js 1.6.0-rc.1 3 9 5 9 14 18

4 of 4

Let’s see an example of element-wise operations for NumPy arrays:

Arrays must have compatible shapes if they were to be operated with each other.

As a rule of thumb:

  1. If there is an operation between two matrices, they should have exactly the same shape.
  2. If there is an operation between a vector and a matrix, then the number of rows or the number of columns should be the same.

Let’s take a look at an operation between a matrix and a single row vector:

The row vector is multiplied element-wise by each row of the matrix.

Let’s see an operation between a matrix and a single column vector:

The column vector is multiplied element-wise by each column of the matrix.


In the next lesson, we will learn some data processing tools for arrays.

Indexing Arrays

Data Processing